package com.weitu.threeSimultaneities.projectApproval.controller;

import com.weitu.accessory.bean.AccessoryPackageInfo;
import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.user.entity.User;
import com.weitu.plugin.PageView;
import com.weitu.threeSimultaneities.projectApproval.entity.*;
import com.weitu.threeSimultaneities.projectApproval.service.ProjectAcceptService;
import com.weitu.threeSimultaneities.projectApproval.service.ProjectApprovalService;
import com.weitu.threeSimultaneities.projectApproval.service.ProjectDesignService;
import com.weitu.threeSimultaneities.projectApproval.service.ProjectFSDService;
import com.weitu.threeSimultaneities.safe.service.SafeService;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * Created by WT on 2017/4/12.
 */
@Controller
@RequestMapping(value = "threeSimultaneities/projectApproval")
public class ProjectApprovalController extends BaseController {
    @Autowired
    private ProjectApprovalService projectApprovalService;
    @Autowired
    private ProjectFSDService projectFSDService;
    @Autowired
    private ProjectDesignService projectDesignService;
    @Autowired
    private AccessoryUtilService accessoryUtilService;
    @Autowired
    private SafeService safeService;

    @Autowired
    private ProjectAcceptService projectAcceptService;

    /***
     * 跳转列表页面
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return BASE_JSP_PATH + "threeSimultaneities/projectApproval/list";
    }
    /***
     * 获取分页数据
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        putParametersIntoMap(map);
        //查询数据总数
        int count = projectApprovalService.selectByParamCount(map);
        //获取分页对象
        DataGridPagination Pagination = DataGridPagination.getInstance(request, count);
        PageView pageView = Pagination.getPageView();//生成pageView分页对象

        map.put("pageView", pageView);
        List<ProjectApproval> dataList = projectApprovalService.selectByParam(map);
        return Pagination.flushDataGridData(dataList);
    }

    /***
     * 添加页面
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(){
        return BASE_JSP_PATH + "threeSimultaneities/projectApproval/add";
    }

    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @Transactional(readOnly = false)
    @SystemLog(module = "项目进程管理", methods = "添加项目进程信息")
    public AjaxResult insertSelective() {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        getAddBasicFieldMap(paramMap);
        paramMap.put("delState", 0);
        int boo=projectApprovalService.insertSelective(paramMap);
        boolean accFlag = AccessoryUtil.saveAccerssoryInfo(paramMap.get("id").toString());
        //判断获取的专业数量
        boolean flag=false;
        if( paramMap.get("specialtyId") instanceof String){//单个专业
            flag=insertSingleSpecialty(paramMap);
        }else{//多个专业
            List<String> specialtyIdList = (List<String>) paramMap.get("specialtyId");
            flag=insertMultipleSpecialty(paramMap, specialtyIdList);
        }
        String projectId=paramMap.get("projectId").toString();//项目ID
        String specialtyNames=paramMap.get("specialtyNames").toString();//项目专业名称
        if (boo == 1 && accFlag && flag) {
            //添加相应专业三同时
            boolean safe=true;
            boolean safeH=true;
            boolean safeF=true;
            if(specialtyNames.contains("安全")){
                safe=addSafeSpecialty(projectId);
            }
            if(specialtyNames.contains("职业卫生")){
                safeH=addSafeSpecialtyH(projectId);
            }
            if(specialtyNames.contains("消防")){
                safeF=addSafeSpecialtyF(projectId);
            }
            if(safe&&safeH&&safeF){
                return success("添加成功");
            }else{
                return fail("添加专业三同时失败！");
            }
        } else {
            return fail("添加失败！");
        }
    }

    /**
     * 打开编辑页面
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String editAjax(Model model, String id,String type){
        //可研阶段
        ProjectFSD projectFSD= projectFSDService.selectByProjectApprovalId(id);
        if(!(projectFSD==null)){
           model.addAttribute("projectFSD", projectFSD);
        }
        //基础设计阶段
        ProjectDesign projectDesign = projectDesignService.selectByProjectApprovalId(id);
        if(!(projectDesign==null)){
            model.addAttribute("projectDesign",projectDesign);
        }
        ProjectAccept projectAccept=projectAcceptService.selectByProjectApprovalId(id);
        if(!(projectAccept==null)){
            model.addAttribute("projectAccept",projectAccept);
        }
        ProjectApproval projectApproval=projectApprovalService.selectById(id);
        //对项目专业ID进行拼接
        if(projectApproval.getProjectSpecialtyList().size()>0){
            String SpecialtyList="";
            for(ProjectSpecialty projectSpecialty:projectApproval.getProjectSpecialtyList()){
                SpecialtyList+=","+projectSpecialty.getSpecialtyId();
            }
            SpecialtyList=SpecialtyList.substring(1);
            model.addAttribute("SpecialtyList",SpecialtyList);
        }
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(id);
        model.addAttribute("accessoryList", accessoryList);
        model.addAttribute("projectApproval", projectApproval);
        return BASE_JSP_PATH + "threeSimultaneities/projectApproval/"+type;
    }

    @SystemLog(module = "项目进程管理", methods = "编辑项目阶段信息")
    @ResponseBody
    @Transactional(readOnly = false)
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public AjaxResult editAjax() throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
            getEditBasicFieldMap(paramMap);
            int boo = projectApprovalService.updateByelective(paramMap);
            boolean accFlag = AccessoryUtil.saveAccerssoryInfo(paramMap.get("id").toString());
        boolean flag=false;
        if( paramMap.get("specialtyId") instanceof String){//单个专业
            flag=insertSingleSpecialty(paramMap);//更新项目专业关联数据
        }else{//多个专业
            List<String> specialtyIdList = (List<String>) paramMap.get("specialtyId");
            flag=insertMultipleSpecialty(paramMap, specialtyIdList);
        }

        String projectId=paramMap.get("projectId").toString();//项目ID
        String specialtyNames=paramMap.get("specialtyNames").toString();//项目专业名称
            if (boo == 1&& accFlag &&flag) {
                //添加相应专业三同时
                boolean safe=true;
                boolean safeH=true;
                boolean safeF=true;
                if(specialtyNames.contains("安全")){
                    safe=addSafeSpecialty(projectId);
                }
                if(specialtyNames.contains("职业卫生")){
                    safeH=addSafeSpecialtyH(projectId);
                }
                if(specialtyNames.contains("消防")){
                    safeF=addSafeSpecialtyF(projectId);
                }
                if(safe&&safeH&&safeF){
                    return success("更新成功");
                }else{
                    return fail("添加专业三同时失败！");
                }
            } else {
                return fail("更新失败！");
        }
    }

    /***
     * 删除项目
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    @Transactional(readOnly = false)
    @SystemLog(module = "项目进程信息管理", methods = "删除项目进程信息")
    public AjaxResult deleteById(String id) {
        int boo = projectApprovalService.deleteByPrimaryKey(id);
        if (boo > 0) {
            return success("删除成功");
        } else {
            return fail("删除失败");
        }
    }

    /**
     * 限制code唯一性
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectByProjectId")
    public AjaxResult findByProjectId(String id) {

        ProjectApproval projectApproval =  projectApprovalService.selectByProjectId(id);

        AjaxResult ajaxResult=new AjaxResult();
        if (null == projectApproval){
            ajaxResult.setSuccess(true);
            ajaxResult.setMessage("项目信息可用");
        }else {
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("项目信息已存在");
        }

        return ajaxResult;
    }

    /**
     *  向关联中插入单个项目专业数据
     * @param paramMap
     * @return
     */
    private boolean insertSingleSpecialty(Map paramMap){
        projectApprovalService.deleteProjectSpecialty(paramMap.get("id").toString());//删除已有项目专业关联数据
        ProjectSpecialty projectSpecialty=new ProjectSpecialty();
        projectSpecialty.setProjectId(paramMap.get("projectId").toString());
        projectSpecialty.setSpecialtyId(paramMap.get("specialtyId").toString());
        int flag= projectApprovalService.insertProjectSpecialty( projectSpecialty);
        return flag>0;
    }
    /**
     * 向关联中插入多个项目专业数据
     * @param paramMap
     * @param specialtyIdList
     * @return
     */
    private boolean insertMultipleSpecialty(Map paramMap, List<String> specialtyIdList){
        projectApprovalService.deleteProjectSpecialty(paramMap.get("id").toString());//删除已有项目专业关联数据
        int count = 0;
        for(String specialtyId:specialtyIdList){
            ProjectSpecialty projectSpecialty=new ProjectSpecialty();
            projectSpecialty.setProjectId(paramMap.get("projectId").toString());
            projectSpecialty.setSpecialtyId(specialtyId);
            count+=projectApprovalService.insertProjectSpecialty( projectSpecialty);
        }
        return  count==specialtyIdList.size();
    }

    /**
     * 添加安全专业三同时主数据
     * @param projectId
     * @return
     */
    private boolean addSafeSpecialty(String projectId) {
        boolean exsit = this.safeService.exsitSafeSpecailty(projectId);
        if (!exsit) {
            Map specialtyMap = new HashMap();
            putAddInfo(specialtyMap);
            specialtyMap.put("projectId", projectId);
            return this.safeService.insertSelective(specialtyMap) > 0;
        } else {
            return true;
        }
    }
    private boolean addSafeSpecialtyH(String projectId) {
        boolean exsit = this.safeService.exsitSafeSpecailtyH(projectId);
        if (!exsit) {
            Map specialtyMap = new HashMap();
            putAddInfo(specialtyMap);
            specialtyMap.put("projectId", projectId);
            return this.safeService.insertSelectiveH(specialtyMap) > 0;
        } else {
            return true;
        }
    }
    private boolean addSafeSpecialtyF(String projectId) {
        boolean exsit = this.safeService.exsitSafeSpecailtyF(projectId);
        if (!exsit) {
            Map specialtyMap = new HashMap();
            putAddInfo(specialtyMap);
            specialtyMap.put("projectId", projectId);
            return this.safeService.insertSelectiveF(specialtyMap) > 0;
        } else {
            return true;
        }
    }
    /**
     * 添加添加时间、人、部门信息参数
     * @param specialtyMap
     */
    private void putAddInfo(Map specialtyMap) {
        String dateTime = DateTimeUtil.formatterDateTime();
        String uuid = IDGenerator.getId();
        User loginUser= getSessionUser();
        String loginUserId=loginUser.getId();
        String loginUserDeptId=loginUser.getDepartment().getId();

        specialtyMap.put("id", uuid);
        specialtyMap.put("addTime", dateTime);
        specialtyMap.put("addUserId", loginUserId);
        specialtyMap.put("addDeptId", loginUserDeptId);
        specialtyMap.put("delState", 0);
    }

}
